<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\entity\ResponseData;
use app\common\service\PlugService;
use app\model\Plugs;
use think\facade\Log;

class Plug extends BaseController
{
    protected PlugService $plugService;

    public function initialize()
    {
        $this->plugService = new PlugService();
    }

    public function installByZip()
    {
        try {
            $file = request()->file('file');

            if (!$file) {
                return ResponseData::error('请选择上传文件');
            }
            return ResponseData::success($this->plugService->installByZip($file));
        } catch (\Exception $e) {
            Log::error('插件安装失败：'.$e->getMessage());
            return ResponseData::error("{$e->getFile()}[{$e->getLine()}]:{$e->getMessage()}");
        }
    }

    public function installByGit($id)
    {
        try {
            return $this->plugService->installByGit($id);
        } catch (\Exception $e) {
            Log::error('Git插件安装失败：'.$e->getMessage());
            return ResponseData::error($e->getMessage());
        }
    }

    public function update($id)
    {
        try {
            $plug = Plugs::findOrFail($id);
            $command = sprintf(
                'cd %s && git pull origin master',
                escapeshellarg('plug/'.$plug->name)
            );
            
            system($command, $code);
            
            if ($code !== 0) {
                throw new \Exception('插件更新失败');
            }
            
            return ResponseData::success('插件更新成功');
        } catch (\Exception $e) {
            Log::error('插件更新失败：'.$e->getMessage());
            return ResponseData::error($e->getMessage());
        }
    }
}
